package com.MTteam.tool;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import com.MTteam.domain.Course;
import com.MTteam.domain.User;

import android.content.Context;
import android.os.Environment;

public class Course_Dao {
	private Context context;

	public Course_Dao(Context con) {
		this.context = con;
	}

	public boolean isReLogin(){
		boolean isLogin=false;
		String name = "user" + ".txt";
		File file = new File(context.getFilesDir(), name);
		if (file.exists() && file.length() != 0) {
			isLogin=true;
		}
		return isLogin;
	}
	public List<Course> getCourses(String user, String pwd,String flag) throws Exception {
		List<Course> courses = new ArrayList<Course>();
		// 解析Json格式字符�?
		try {
			String result = getConnection(user, pwd,flag);
			JSONArray jsonArray = new JSONArray(result);
			for (int i = 0; i < jsonArray.length(); i++) {
				Course course = new Course();
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				course.setTime(jsonObject.getString("time"));
				course.setMon(jsonObject.getString("mon"));
				course.setTues(jsonObject.getString("tues"));
				course.setWednes(jsonObject.getString("wednes"));
				course.setThurs(jsonObject.getString("thurs"));
				course.setFri(jsonObject.getString("fri"));
				course.setSatur(jsonObject.getString("satur"));
				course.setSun(jsonObject.getString("sun"));
				courses.add(course);
			}
		} catch (Exception e) {
			e.fillInStackTrace();
		}
		return courses;
	}

	public String getConnection(String user, String pwd,String flag) {
		String result = "";
		String name = "course" + user + ".txt";
		File file = new File(context.getFilesDir(), name);
		if (file.exists() && file.length() != 0&&flag.equals("cache")) {
			try {
				FileInputStream fis = new FileInputStream(file);
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len;
				while ((len = fis.read(buffer)) != -1) {
					bos.write(buffer, 0, len);
				}
				byte[] content = bos.toByteArray();
				result = new String(content);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("user", user));
			params.add(new BasicNameValuePair("pwd", pwd));
			// 建立连接
			HttpPost request = new HttpPost(
					"http://wcl92.eicp.net/Iknow/CourseServlet");
			// 设置字符�?
			try {
				request.setEntity(new UrlEncodedFormEntity(params));
				// 设置头部
				request.setHeader("X-Online-Host", "http://wcl92.eicp.net/");
				// 执行请求，获取响�?
				HttpResponse response = new DefaultHttpClient()
						.execute(request);
				/*
				 * // 设置超时 HttpParams myParams = new BasicHttpParams();
				 * HttpConnectionParams.setConnectionTimeout(myParams, 3000);
				 * HttpConnectionParams.setSoTimeout(myParams, 5000);
				 */
				if (response.getStatusLine().getStatusCode() == 200) {
					result = EntityUtils.toString(response.getEntity());
					if(result.length()>116){
						// 缓存
						file = new File(context.getFilesDir(), name);
						FileOutputStream fos = new FileOutputStream(file);
						fos.write(result.getBytes());
						fos.flush();
						fos.close();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public User getUser(String user, String pwd) throws Exception {
		User u = new User();
		// 解析Json格式字符串
		try {
			String result = getUserConnection(user, pwd);
			JSONArray jsonArray = new JSONArray(result);
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				u.setGrade(jsonObject.getString("grade"));
				u.setMajor(jsonObject.getString("major"));
				u.setName(jsonObject.getString("name"));
				u.setNumber(jsonObject.getString("number"));
			}
		} catch (Exception e) {
			e.fillInStackTrace();
		}
		return u;
	}

	public String getUserConnection(String user, String pwd) {
		String result = "";
		String name = "user" + user + ".txt";
		File file = new File(context.getFilesDir(), name);
		if (file.exists() && file.length() != 0) {
			try {
				FileInputStream fis = new FileInputStream(file);
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len;
				while ((len = fis.read(buffer)) != -1) {
					bos.write(buffer, 0, len);
				}
				byte[] content = bos.toByteArray();
				result = new String(content);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {

			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("user", user));
			params.add(new BasicNameValuePair("pwd", pwd));
			// 建立连接
			HttpPost request = new HttpPost(
					"http://wcl92.eicp.net/Iknow/UserServlet");
			// 设置字符集
			try {
				request.setEntity(new UrlEncodedFormEntity(params));
				// 设置头部
				request.setHeader("X-Online-Host", "http://wcl92.eicp.net/");
				// 执行请求，获取响应
				HttpResponse response = new DefaultHttpClient()
						.execute(request);
				/*
				 * // 设置超时 HttpParams myParams = new BasicHttpParams();
				 * HttpConnectionParams.setConnectionTimeout(myParams, 3000);
				 * HttpConnectionParams.setSoTimeout(myParams, 5000);
				 */
				if (response.getStatusLine().getStatusCode() == 200) {
					result = EntityUtils.toString(response.getEntity());
					if(result.length()>47){
						// 缓存
						file = new File(context.getFilesDir(), name);
						FileOutputStream fos = new FileOutputStream(file);
						fos.write(result.getBytes());
						fos.flush();
						fos.close();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}
}